package com.moli.iov.down.command.codec.decode.decoders;

import com.moli.iov.down.command.codec.decode.bean.UpgradeResBean;
import com.moli.iov.exception.BusinessException;
import com.moli.iov.util.ByteArrayUtil;
import org.apache.commons.lang.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * <p>
 *  恒领远程升级命令应答 解码
 * </p>
 *
 * @author: zql
 * @Date: 2019/4/16 14:14
 */
@Component("upgradeDecoder")
@Scope("prototype")
public class UpgradeDecoder extends BaseDecoder {

    protected final Logger log = LoggerFactory.getLogger(this.getClass());

    public UpgradeResBean decode(byte[] data){
        try{
            //状态 0x00:下载 0x01:升级
            byte[] status = ArrayUtils.subarray(data, 0, 1);
            data = ArrayUtils.subarray(data, 1, data.length);

            //时间
            byte[] date = ArrayUtils.subarray(data, 0, 6);
            data = ArrayUtils.subarray(data, 6, data.length);

            //流水号
            byte[] serialNumber = ArrayUtils.subarray(data,0 ,2);
            data = ArrayUtils.subarray(data, 2, data.length);

            //升级状态
            byte[] upgradeStatus = ArrayUtils.subarray(data, 0, 1);
            data = ArrayUtils.subarray(data, 1, data.length);

            //升级日志
            String upgradeLog = ByteArrayUtil.asciiToStr(data);

            UpgradeResBean  upgradeResBean = new UpgradeResBean();
            upgradeResBean.setStatus(status[0]);
            upgradeResBean.setDate(this.dateDecode(date));
            upgradeResBean.setSerialNumber(this.serialNumberDecode(serialNumber));
            upgradeResBean.setUpgradeStatus(upgradeStatus[0]);
            upgradeResBean.setUpgradeLog(upgradeLog);

            return upgradeResBean;
        }catch(Exception e){
            logger.error("恒领远程升级命令应答 解码 异常", e);
            throw new BusinessException("恒领远程升级命令应答 解码失败");
        }
    }
}
